from flask import Blueprint,render_template,request,g,redirect,url_for
from  .forms import QuestionForm,AnswerForm
from models import QuestionModel,AnswerModel
from exts import db
from decorators import login_required

bp = Blueprint('qa',__name__,url_prefix='/')#'/'首页蓝图

#http://127.0.0.1:5000
@bp.route('/')
def index():
    #对所有问题进行倒序排列
    questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()
    return render_template("index.html",questions=questions)



@bp.route('/qa/public',methods=['POST','GET'])
@login_required
def public_qa():
    if request.method == 'POST':
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(title=title,content=content,author=g.user)
            db.session.add(question)
            db.session.commit()
            return redirect('/')
        else:
            print(form.errors)
            return redirect(url_for('qa.public_qa'))
    else:
        return render_template('public_question.html')


@bp.route('/qa/detail/<qa_id>')
def qa_detail(qa_id):
    question = QuestionModel.query.get(qa_id)
    return render_template("detail.html",question=question)

@bp.route('/answer/public',methods=['POST'])
@login_required
def public_answer():
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data
        question_id= form.question_id.data
        answer = AnswerModel(question_id=question_id,content=content,author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for('qa.qa_detail',qa_id=question_id))

    else:
        print(form.errors)
        return redirect(url_for('qa.qa_detail',qa_id=request.form.get('question_id')))

@bp.route('/search')
def search():
    #怎么拿到用户的关键字？
    #1.查询字符串 /search?q=flask
    #2.关键字固定在路径 /search/<q>
    #3.post,request.form去拿参数
    q = request.args.get('q')
    questions = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template("index.html",questions=questions)